package com.buba.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buba.mapper.DeviceTypeMapper;
import com.buba.mapper.PlaceForStorageMapper;
import entity.device.DeviceType;
import com.buba.mapper.FileMapper;
import com.buba.mapper.ImageMapper;
import entity.device.EquipmentArchives;
import com.buba.mapper.EquipmentArchivesMapper;
import com.buba.service.EquipmentArchivesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import entity.device.PlaceForStorage;
import entity.device.dto.EquipmentQueryWrapper;
import entity.device.vo.EquipmentAllVo;
import entity.sparemanage.dto.EquipmentArchivesDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import entity.device.dto.*;
import entity.sparemanage.File;
import entity.sparemanage.Image;
import entity.system.CodeRules;
import org.springframework.stereotype.Service;
import utils.PageResult;
import java.util.ArrayList;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import utils.pageutil.MyPageHelper;
import utils.pageutil.PageRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author beisheng
 * @since 2023-05-18
 */
@Service
public class EquipmentArchivesServiceImpl extends ServiceImpl<EquipmentArchivesMapper, EquipmentArchives> implements EquipmentArchivesService {
    @Autowired
    private EquipmentArchivesMapper equipmentArchivesMapper;

    @Autowired
    private PlaceForStorageMapper placeForStorageMapper;

    @Autowired
    private feign.systemFeign systemFeign;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private DeviceTypeMapper deviceTypeMapper;
    /* *
     * @Author: beisheng
     * @Descriprion: 分页模糊查询设备信息
     * @Date: 2023/5/22 10:50
     * @Return: common.R
     * @Param: [equipmentArchives]
     */

    @Override
    public PageResult selAllequArch(EquipmentArchivesDto equipmentArchives) {
        EquipmentQueryWrapper equipmentQueryWrapper = new EquipmentQueryWrapper();
        Page<EquipmentArchives> equipmentArchivesPage = new Page<>(equipmentArchives.getPage(),equipmentArchives.getPageSize());
        QueryWrapper<EquipmentArchives> queryWrapper = equipmentQueryWrapper.queryWrapper(equipmentArchives);
        Page<EquipmentArchives> archivesPage = equipmentArchivesMapper.selectPage(equipmentArchivesPage,queryWrapper);
        List<EquipmentArchives> archivesl = equipmentArchivesMapper.selectList(new QueryWrapper<EquipmentArchives>().eq("delete_flag", 0));
        List<EquipmentArchives> records = archivesPage.getRecords();
        List<EquipmentAllVo> equipmentAllVos = new ArrayList<>();
        for (EquipmentArchives record : records) {
            EquipmentAllVo equipmentAllVo = new EquipmentAllVo();
            PlaceForStorage placeForStorage = placeForStorageMapper.selectOne(new QueryWrapper<PlaceForStorage>().eq("delete_flag", 0).eq("id", record.getPlaceForStorage()));
            DeviceType deviceType = deviceTypeMapper.selectOne(new QueryWrapper<DeviceType>().eq("delete_flag", 0).eq("id", record.getDeviceType()));
            if (placeForStorage!=null){
                equipmentAllVo.setPlaceForStorageName(placeForStorage.getLocationName());
            }
            if (deviceType != null){
                equipmentAllVo.setDeviceTypeName(deviceType.getTypeName());
            }
            BeanUtils.copyProperties(record, equipmentAllVo);
            equipmentAllVos.add(equipmentAllVo);
        }
        return new PageResult(equipmentArchives.getPage(),equipmentArchives.getPageSize(),archivesl.size(),equipmentAllVos);
    }
    /*
     * @Author atlong
     * @Description 分页模糊查
     * @Date 2023/5/30 19:13
     * @Param [equipmentArchivesDto]
     * @return utils.pageutil.PageResult
     **/
    @Override
    public utils.pageutil.PageResult selEquipmentArchives(EquipmentArchivesDto equipmentArchivesDto) {
        EquipmentArchivesQueryWrapper equipmentArchivesQueryWrapper = new EquipmentArchivesQueryWrapper();
        QueryWrapper<EquipmentArchives> conditional = equipmentArchivesQueryWrapper.conditional(equipmentArchivesDto);
        PageRequest pageRequest = new PageRequest(equipmentArchivesDto.getPage(), equipmentArchivesDto.getPageSize());
        MyPageHelper.startPage(pageRequest);
        List<EquipmentArchives> list = equipmentArchivesMapper.selectList(conditional);
        utils.pageutil.PageResult pageResult = MyPageHelper.getPageResult(list);
        return pageResult;
    }

    /**
     * @return common.R
     * @Author atlong
     * @Description 添加设备档案信息
     * @Date 2023/6/5 21:16
     * @Param [add]
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addEquipmentArchives(addEquipmentArchivesDto add) {
        //1.查询编码生成规则，进行生成编码
        CodeRules bj = systemFeign.selAllRules("SB");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(bj.getDateTime());
        String format = simpleDateFormat.format(new Date());
        List<EquipmentArchives> spareLedgerList = equipmentArchivesMapper.selectList(new QueryWrapper<EquipmentArchives>().eq("delete_flag", 0));
        String code = bj.getPrefix() + format + "0" + (spareLedgerList.size() + 1);
        //2.添加数据到设备表
        EquipmentArchives equipmentArchives = new EquipmentArchives();
        /**
         *将add对象的属性值复制到equipmentArchives对象中。需要注意的是，
         * 这个方法只会复制两个对象中属性名相同且类型相同的属性值，
         * 如果属性名或类型不同，则不会被复制。同时，如果属性值为null，则也不会被复制。
         **/
        BeanUtils.copyProperties(add, equipmentArchives);
        equipmentArchives.setEquipmentNumber(code);
        equipmentArchives.setDeviceType(add.getDeviceType().get(add.getDeviceType().size() - 1));
        equipmentArchives.setUserDepartment(add.getUserDepartment().get(add.getUserDepartment().size() - 1));
        equipmentArchives.setDeleteFlag(0);
        equipmentArchives.setCreateTime(new Date());
        equipmentArchives.setUpdateTime(new Date());
        try {
            equipmentArchivesMapper.insert(equipmentArchives);
            // 执行其他操作
        } catch (Exception e) {
            // 发生异常，手动回滚事务
            throw new RuntimeException("新增设备失败", e);
        }

        //3.如果有图片，那么上传到图片表
        List<imgList> imgLists = add.getImgList();
        if (imgLists != null) {
            for (imgList imgList : imgLists) {
                Image image = new Image();
                image.setAssociationId(equipmentArchives.getArchivesId());
                image.setImageAddress(imgList.getUrl());
                image.setImageType(1);
                image.setCreateTime(new Date());
                image.setUpdateTime(new Date());
                image.setDeleteFlag(0);
                try {
                    imageMapper.insert(image);
                } catch (Exception e) {
                    throw new RuntimeException("图片新增失败", e);
                }
            }
        }
        //4.如果有关联文档，那么上传到文件表
        List<fileList> fileLists = add.getFileList();
        if (fileLists != null) {
            for (fileList fileList : fileLists) {
                File file = new File();
                file.setAssociationId(equipmentArchives.getArchivesId());
                file.setFileAddress(fileList.getUrl());
                file.setFileType(1);
                file.setCreateTime(new Date());
                file.setUpdateTime(new Date());
                file.setDeleteFlag(0);
                try {
                    fileMapper.insert(file);
                } catch (Exception e) {
                    throw new RuntimeException("文件新增失败", e);
                }
            }
        }

    }

    /**
     * @return boolean
     * @Author atlong
     * @Description //批量删除设备信息
     * @Date 2023/6/6 15:48
     * @Param [ids]
     **/
    @Override
    public boolean delEquipmentArchives(List<Integer> ids) {
        int i = equipmentArchivesMapper.deleteBatchIds(ids);
        return i > 0;
    }
}
